package controller

import (
	"gin_template/core/app"
	"gin_template/core/jwt"
	"gin_template/data/e"
	"gin_template/models"
	"gin_template/services"
	"net/http"

	"github.com/gin-gonic/gin"
)

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录
// @Tags 用户登录
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer 用户令牌"
// @Param object body models.User false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} app.Response
// @Router /Login [post]
func Login(c *gin.Context) {
	appG := app.Gin{C: c}
	var userModel = models.AuthUser{}
	httpCode, errCode, validRes := app.BindAndValidWithError(c, &userModel)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, validRes)
		return
	}
	result, err := services.Login(&userModel)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
	} else {
		//账号密码验证成功
		authToken, _ := jwt.GenToken(result.Account, result.Id)
		appG.Response(http.StatusOK, e.SUCCESS, authToken)
	}

}

// Register 用户注册
// @Summary 用户注册
// @Description 用户注册
// @Tags 用户注册
// @Accept application/json
// @Produce application/json
// @Param Authorization header string false "Bearer 用户令牌"
// @Param object body models.User false "查询参数"
// @Security ApiKeyAuth
// @Success 200 {object} app.Response
// @Router /Register [post]
func Register(c *gin.Context) {
	appG := app.Gin{C: c}
	var userModel = models.User{}
	//if id, isExist := c.Get(jwt.CtxUserIdKey); !isExist {
	//	appG.Response(http.StatusOK, e.ERROR_AUTH_INVALID, "无效的Token")
	//} else {
	//	userModel.Id = id.(int)
	//}
	httpCode, errCode, validRes := app.BindAndValidWithError(c, &userModel)
	if errCode != e.SUCCESS {
		appG.Response(httpCode, errCode, validRes)
		return
	}
	userId, err := services.Register(&userModel)
	if err != nil {
		appG.Response(http.StatusInternalServerError, e.ERROR, err.Error())
	} else {
		appG.Response(http.StatusOK, e.SUCCESS, userId)
	}

}
